from fastapi import APIRouter
from pydantic import BaseModel, EmailStr
from typing import Union
from exts.email_ import send_email
import random
import string
import threading
import time
from database import db
import io
import cv2
from PIL import Image
import base64
router = APIRouter()

class Student(BaseModel):
    name: Union[str, None] = None
    password: str
    sno: str
    class_id: Union[int, None] = None
    email:Union[str, None] = None
    avatar: Union[str, None] = None
#注册
@router.post("/student_register")
async def student_register(student: Student):
    name=student.name
    pwd=student.password
    sno=student.sno
    class_id=student.class_id
    email=student.email
    if len(sno) !=11:
        return {
            'code': 400,
            'msg': '您没有资格注册'
        }
    exit=await  db.Student.filter(sno=sno)
    if exit:
        return {
            'code': 400,
            'msg' : '该用户已注册'
        }
    with open(r'./static/image/默认头像.png', 'rb') as f:
        avatar=f.read()
    avatar=resize_img(avatar,(100,100))
    exit=await db.User.filter(
        name=name,
        num=sno,
        sf='student',
    )
    if exit:
        new_student=await db.Student.create(
            name=name,
            pwd=pwd,
            sno=sno,
            avatar_blob=avatar,
            email=email,
            class_id=class_id
        )
        return {
            'code' : 200,
            'msg' : '注册成功'
        }
    else:
        return{
            'code':400,
            'msg' : '您没有资格注册'
        }
#发送验证码
@router.post("/email")
async def email(to_ad :str):
    code=string.ascii_letters+string.digits
    ver_code=''.join(random.choice(code) for _ in range(6))
    threading.Thread(target=send_email,args=(to_ad,'验证码',ver_code)).start()
    return {
        "code":200,
        'msg':ver_code,
    }
#查询学生信息
@router.get("/get_student")
async def get_student(sno:str):
    student=await db.Student.filter(sno=sno).first()
    if student:
        student.avatar_blob=base64.b64encode(student.avatar_blob)
        return {
            'code':200,
            'msg':student
        }
    else:
        return {
            'code':400,
            'msg':'用户尚未注册'
        }
#查询教师信息
@router.get("/get_teacher")
async def get_teacher(num:str):
    teacher=await db.Teacher.filter(num=num)
    if teacher:
        return {
            'code':200,
            'msg':teacher
        }
    else:
        return {
            'code':400,
            'msg':'用户尚未注册'
        }

#更改图片尺寸
def resize_img(img,size):
    with Image.open(io.BytesIO(img)) as img:
        img1=img.resize(size)
        output = io.BytesIO()
        img1.save(output, format=img.format)
        return  output.getvalue()